package org.example.controller;

import cn.hutool.core.io.IoUtil;
import org.example.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/*
用户信息的Controller
 */
@RestController
public class UserController {

    @RequestMapping("/list")
    public List<User> list() throws Exception {
        // 1.加载并读取user.txt 文件，读取用户数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");

        // 检查文件是否存在
        if (in == null) {
            throw new RuntimeException("user.txt 文件未找到");
        }

        ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());

        // 2.解析用户数据，封装为User对象 -> list集合
        List<User> userList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (String line : lines) {
            // 跳过空行
            if (line == null || line.trim().isEmpty()) {
                continue;
            }

            try {
                String[] parts = line.split(",");
                if (parts.length < 6) {
                    continue; // 格式不正确的行跳过
                }

                Integer id = Integer.parseInt(parts[0].trim());
                String username = parts[1].trim();
                String password = parts[2].trim();
                String name = parts[3].trim();
                Integer age = Integer.parseInt(parts[4].trim());
                LocalDateTime updateTime = LocalDateTime.parse(parts[5].trim(), formatter);

                userList.add(new User(id, username, password, name, age, updateTime));
            } catch (Exception e) {
                // 记录错误但继续处理其他行
                System.err.println("解析用户数据出错，行内容: " + line + ", 错误: " + e.getMessage());
            }
        }

        // 3.返回数据(json)
        return userList;
    }
}
